#!/usr/bin/python3.6
import typer
import sys
import os
import xlsxwriter as xw
from datetime import (date, datetime, timezone, timedelta)
from pathlib import Path
import time
import uuid

import icalendar
from zhdate import ZhDate
sys.path.append(sys.path[0])
from SlurpFile import( pConM, GetRndHex)

app = typer.Typer()
td = date.today()
yri = str(td.strftime("%Y"))

def CreateWSheet(wsheet, dateO, dictFmt, listLC):
  """ """  # <<<
  wsheet.set_zoom(120)
  wsheet.set_footer('&C&16&A')
  wsheet.set_row(0, 15)
  wsheet.set_row(1, 16)
  wsheet.set_column(0, 0, 8)
  wsheet.set_column(1, 1, 0.5)
  wsheet.set_column(2, 8, 6)
  wsheet.merge_range(0, 2, 0, 8, "")
  wsheet.write_datetime(0, 2, dateO, dictFmt.get('ft0'))
  wsheet.merge_range(1, 2, 1, 8, "Compact Calendar", dictFmt.get('ftCCal'))

  SWSheetRow_i = 2
  wsheet.set_row(SWSheetRow_i, 25)
  wsheet.write_datetime(SWSheetRow_i, 8, dateO, dictFmt.get('ftd'))
  for i0 in range(2, 8):
    wsheet.write_formula(SWSheetRow_i, i0, '=INDIRECT("RC[+1]",0)-1', dictFmt.get('ftd'))

  SWSheetRow_i += 1
  while SWSheetRow_i < 25:
    wsheet.set_row(SWSheetRow_i, 28)
    i2 = SWSheetRow_i + 1
    i2s = str(i2)
    formulaStr = f"{{=IF(SUM(1*(DAY(C{i2s}:I{i2s})=1))>0,I{i2s}, \"\")}}"
    wsheet.write_formula(SWSheetRow_i, 0, formulaStr, dictFmt.get('ftm'))
    fstr2 = '=INDIRECT("R[-1]C[+6]", 0)+1'
    wsheet.write_formula(SWSheetRow_i, 2, fstr2, dictFmt.get('ftd'))
    for i1 in range(3, 9):
      fstr3 = '=INDIRECT("RC[-1]", 0)+1'
      wsheet.write_formula(SWSheetRow_i, i1, fstr3, dictFmt.get('ftd'))
    SWSheetRow_i += 1

  wsheet.conditional_format('A3:A25', {'type': 'formula', 'criteria': 'IF(MOD(MONTH(I3), 3)=1, 1, 0)', 'format': dictFmt.get('ftMon1')})

  for d5552 in listLC:
    fstr6943 = f"IF(C3=DATE({d5552.year}, {d5552.month}, {d5552.day}), 1, 0)"
    wsheet.conditional_format('C3:I25', {'type': 'formula', 'criteria': fstr6943, 'format': dictFmt.get('ft_lunar')})

  wsheet.conditional_format('C3:I25', {'type': 'formula', 'criteria': 'IF(DAY(C3)=1, 1, 0)', 'format': dictFmt.get('ft_1stday')})
  wsheet.conditional_format('C3:I25', {'type': 'formula', 'criteria': 'DAY(C3)>DAY(C4)', 'format': dictFmt.get('ft_uline')})



############################################
#  end of def; why nobody do this?
############################################
# >>>


#####################
#  code main block  #
#####################

@app.command()
def main(
    yr: str = yri,
    datefont: str = "Courier New",
    monfont: str = "Garamond",
    OfficeOpen: bool = False,
    ):
  Lyear = [d1599 for d1599 in yr.split(",")]
  str2 = "_".join(Lyear[0:6])
  fname2 = f"{str2}.{GetRndHex(7)}.xlsx"
  


  with xw.Workbook(fname2) as wk:
    """ """  # <<<
    pConM(f"{'-i-writing into ':>16}{fname2}", Fgnd=4)
    ft0 = wk.add_format({'num_format': 'dd mmm yyyy'})
    ftd = wk.add_format({'num_format': 'dd', 'font_size': 20, 'align': 'center', 'text_wrap': True, 'font_name': datefont })
    ftm = wk.add_format({'num_format': 'mmm', 'font_outline': True, 'font_size': 24, 'align': 'center', 'font_name': monfont})
    ftCCal = wk.add_format({
        'align': 'center',
        'bg_color': '#5757ff',
        'bold': True,
        'border': 0,
        'color': '#f4f4ff',
        'font': monfont,
        'size': 14,
        'text_wrap': True
    })
    #      'font': 'Courier New',

    ft_1stday = wk.add_format({'bold': True, 'bg_color': '#ff9966'})
    ft_uline = wk.add_format({'bottom': 6, 'bottom_color': '#9900cc', 'color': '#5f021f'})
    ftMon1 = wk.add_format({'bg_color': '#90f9b7'})
    ft_lunar = wk.add_format({'bold': True, 'bg_color': '#ff7a90', 'color': '3f000b', 'font_outline':True})
    dFt = {'ft0': ft0}
    dFt.update(ftCCal=ftCCal)
    dFt.update(ftd=ftd)
    dFt.update(ftm=ftm)
    dFt.update(ft_1stday=ft_1stday)
    dFt.update(ft_lunar=ft_lunar)
    dFt.update(ft_uline=ft_uline)
    dFt.update(ftMon1=ftMon1)
    LCal=list()
    LY2=list()
    for yr in Lyear:
      yr0 = int(yr)
      LY2.append(yr0)
      LY2.append(yr0+1)
    LY3 = mylist = list( dict.fromkeys(LY2) )

    Lld = [[1,1], [5,5], [8, 15]]

    for yr in LY3:
      for md in Lld:
        (mn, dy) = md
        try:  # if raise error, likely due to lnD==30 for a 29-day month
          ld3176 = ZhDate(yr, mn, dy)
        except TypeError as e:
          dy -= 1
          ld3176 = ZhDate(yr, mn, dy)
        else:
          pass
        d1754 = ld3176.to_datetime()
        LCal.append(d1754)


    for yr in Lyear:
      yr0 = int(yr)

      for mi in range(1, 13):
        tf1 = date(year=yr0, month=mi, day=1)
        dow = tf1.weekday()
#         i6528 = (dow+1)%7  # if to make 1 week buffer for Sunday of 1st day of month
#         i6529 = i6528 + 1  # 
        i6529 = dow+2
        td0 = timedelta(i6529)
        tf2 = tf1 - td0
        ywStr2 = tf1.strftime("%yMn%m")
        ws = wk.add_worksheet(ywStr2)
        CreateWSheet(ws, tf2, dFt, LCal)

# >>>

  if OfficeOpen:
    os.system("/usr/bin/libreoffice --calc --view " + fname2 + " & ")
  else:
    pass


if __name__ == "__main__":
  app()
